<template>
  <div class="v-identity">
    <div class="title">{{ $t('message.writeIdentityInfo') }}</div>
    <!--学校-->
    <div class="label">{{$t('message.personalIdentitySchool')}}:</div>
    <!--请填写学校名称-->
    <input type="text" v-model.trim="data.school" @click.stop="onClick('school')" @keydown.40="selectDownList('school')" @keydown.38.prevent="selectUpList('school')" @keydown.enter="keyEnter('school')" class="input input-long" spellcheck="false" :placeholder="this.$t('message.pleaseFillSchoolName')"/>
    <ul class="select-dropdown" ref="dropdown" v-if="schoolList.length > 0">
      <li v-for="(item, index) in schoolList" :key="index" @click="selectItem('school', index)" @mouseenter="mouseEnter('school', index)" :class="{ active: schoolIndex === index }">{{ item.name }}</li>
    </ul>
    <div class="error-tips" v-if="schoolStatus === 2">
      {{$t('message.inputSchool')}}
    </div>
    <!--学区-->
    <div class="label">{{$t('message.personalIdentityDistrict')}}:</div>
    <input type="text" v-model.trim="data.schoolDistrict" @click.stop="onClick('schoolDistrict')" @keydown.40="selectDownList('schoolDistrict')" @keydown.38.prevent="selectUpList('schoolDistrict')" @keydown.enter="keyEnter('schoolDistrict')" spellcheck="false" class="input input-long" :placeholder="this.$t('message.pleaseFillSchoolDistrict')" />
    <ul class="select-dropdown" ref="dropdown" v-if="schoolDistrictList.length > 0">
      <li v-for="(item, index) in schoolDistrictList" :key="index" @click="selectItem('schoolDistrict', index)" @mouseenter="mouseEnter('schoolDistrict', index)" :class="{ active: schoolDistrictIndex === index }">{{ item.name }}</li>
    </ul>
    <div class="error-tips" v-if="schoolDistrictStatus === 2">
      {{ $t('message.inputSchoolDistrict') }}
    </div>
    <!--年级-->
    <div class="label">{{$t('message.personalIdentityGrade')}}:</div>
    <input type="text" v-model="data.grade" class="input input-long" :placeholder="this.$t('message.pleaseFillGrade')" />
    <div class="error-tips" v-if="gradeError">
      {{$t('message.inputGrade')}}
    </div>
    <!--现住地址-->
    <div class="label">{{ $t('message.personalIdentityAddressNow') }}:</div>
    <input type="text" v-model="data.currentAddress" class="input input-long" :placeholder="this.$t('message.pleaseFillAddressNowHolder')" />
    <div class="error-tips" v-if="currentAddressError">
      {{$t('message.rightLiveAddress')}}
    </div>
    <!--上传身份证正面照片-->
    <div>
      <div class="upload">
        <v-upload-image @uploadImage="upload('identify', $event)" :image="data.identifyCard">
          <span slot="text">{{ $t('message.personalIdentityPleaseUploadIdentificationPicture') }}</span>
          <span slot="titleTip">({{ $t('message.PersonalIdentityAuthenticationOrIdentityCopy') }})</span>
          <img slot="photo" src="../../assets/images/register/identity_card_front.png" :alt="this.$t('message.identificationPicture')" />
        </v-upload-image>
      </div>
      <div class="error-tips" v-if="uploadIdentityImgError">
        {{$t('message.personalIdentityPleaseUploadIdentificationPicture')}}
      </div>
    </div>
    <!--本人手持身份证照片-->
    <div>
      <div class="upload">
        <v-upload-image @uploadImage="upload('selfHold', $event)" :image="data.selfHoldCard">
          <span slot="text">{{ $t('message.personalIdentityUploadSelfHoldCard') }}</span>
          <img slot="photo" src="../../assets/images/register/self_card.png" :alt="this.$t('message.personalIdentityStudentCardPicture')" />
        </v-upload-image>
      </div>
      <div class="error-tips" v-if="uploadSelfHoldImgError">
        {{ $t('message.personalIdentityUploadSelfHoldCard') }}
      </div>
    </div>
    <!--上传学生卡照片-->
    <div>
      <div class="upload">
        <v-upload-image @uploadImage="upload('student', $event)" :image="data.studentCard">
          <span slot="text">{{$t('message.personalIdentityUploadStudentCardPicture')}}</span>
          <img slot="photo" src="../../assets/images/register/sutdent_card.png" :alt="this.$t('message.personalIdentityStudentCardPicture')" />
        </v-upload-image>
      </div>
      <div class="error-tips" v-if="uploadStudentImgError">
        {{$t('message.personalIdentityUploadStudentCardPicture')}}
      </div>
    </div>
  </div>
</template>

<script>
import VUploadImage from '@/components/base/VUploadImage'

export default {
  name: 'VIdentity',
  components: {
    VUploadImage
  },
  props: {
    parentData: {
      type: Object,
      default () {
        return {
          school: '',
          schoolDistrict: '',
          grade: '',
          currentAddress: '',
          identifyCard: '',
          studentCard: '',
          selfHoldCard: ''
        }
      }
    }
  },
  data () {
    return {
      data: {
        school: this.parentData.school || '',
        schoolDistrict: this.parentData.schoolDistrict || '',
        grade: this.parentData.grade || '',
        currentAddress: this.parentData.currentAddress || '',
        identifyCard: this.parentData.identifyCard || '',
        studentCard: this.parentData.studentCard || '',
        selfHoldCard: this.parentData.selfHoldCard || ''
      },
      // 学校
      schoolStatus: 0,
      schoolList: [],
      schoolSelect: false,
      schoolIndex: -1,
//        学区
      schoolDistrictStatus: 0,
      schoolDistrictList: [],
      schoolDistrictSelect: false,
      schoolDistrictIndex: -1,
//        年级
      gradeError: false,
      gradeStatus: 0,
//        现住地址
      currentAddressError: false,
      currentAddressStatus: 0,
//        身份证相片
      uploadIdentityImgError: false,
      uploadIdentityImgStatus: 0,
//        学生证相片
      uploadStudentImgError: false,
      uploadStudentImgStatus: 0,
//        本人手持相片
      uploadSelfHoldImgError: false,
      uploadSelfHoldImgStatus: 0,
      test: []
    }
  },
  computed: {
    isHandParent () {
      if (this.schoolStatus === 1 && this.schoolDistrictStatus === 1 && this.gradeStatus === 1 && this.currentAddressStatus === 1 && this.uploadIdentityImgStatus === 1 && this.uploadStudentImgStatus === 1 && this.uploadSelfHoldImgStatus === 1) {
        return 'ok'
      } else {
        return 'no'
      }
    },
    lang () {
      if (window.lang === 'cn') {
        return 1
      } else if (window.lang === 'en') {
        return 3
      } else {
        return 2
      }
    }
  },
  watch: {
    isHandParent (val) {
      if (val === 'ok') {
        this.$emit('change-params', this.data)
      } else if (val === 'no') {
        this.$emit('change-params', 'no')
      }
    },
    // 学校
    'data.school' (val) {
      // 取消请求，防止网络太慢造成列表弹出
      this.cancelToken()
      if (val === '') {
        this.schoolStatus = 2
        this.schoolList = []
      } else {
        this.schoolStatus = 1
        if (!this.schoolSelect) {
          this.schoolIndex = -1
          this.getSchoolList()
        } else {
          this.schoolSelect = false
        }
      }
    },
    // 学区
    'data.schoolDistrict' (val) {
      // 取消请求，防止网络太慢造成列表弹出
      this.cancelToken()
      if (val === '') {
        this.schoolDistrict = 2
        this.schoolDistrictList = []
      } else {
        this.schoolDistrictStatus = 1
        if (!this.schoolDistrictSelect) {
          this.schoolDistrictIndex = -1
          this.getSchoolDistrictList()
        } else {
          this.schoolDistrictSelect = false
        }
      }
    },
    //      年级
    'data.grade' (val) {
      clearTimeout(this.gradeTimer)
      this.gradeTimer = setTimeout(() => {
        if (/^\s*$/g.test(val)) {
          this.gradeStatus = 2
          this.gradeError = true
        } else {
          this.gradeStatus = 1
          this.gradeError = false
        }
      }, 900)
    },
    //      现住地址
    'data.currentAddress' (val) {
      clearTimeout(this.currentAddressTimer)
      this.currentAddressTimer = setTimeout(() => {
        if (/^\s*$/g.test(val)) {
          this.currentAddressStatus = 2
          this.currentAddressError = true
        } else {
          this.currentAddressStatus = 1
          this.currentAddressError = false
        }
      }, 900)
    }
  },
  methods: {
    // 获取学校列表
    getSchoolList () {
      let ajax = this.$ajax.getSchool({key_word: this.data.school, type: this.lang})
      this.source = ajax.source
      ajax.get.then((res) => {
        if (res.code === 200) {
          this.schoolList = res.data
        } else {
          // 清空学校的列表并且隐藏
          this.schoolList = []
        }
      }).catch((err) => {
      })
    },
    // 获取学区列表
    getSchoolDistrictList () {
      let ajax = this.$ajax.getSchoolArea({key_word: this.data.schoolDistrict, type: this.lang})
      this.source = ajax.source
      ajax.get.then((res) => {
        if (res.code === 200) {
          this.schoolDistrictList = res.data
        } else {
          // 清空学区的列表并且隐藏
          this.schoolDistrictList = []
        }
      }).catch((err) => {
      })
    },
    // 鼠标点击学校
    selectItem (attr, index) {
      this.data[attr] = this[attr + 'List'][index].name
      this[attr + 'Select'] = true
      this[attr + 'List'] = []
    },
    // 鼠标移入下拉框
    mouseEnter (attr, index) {
      this[attr + 'Index'] = index
    },
    // 按下方向键向下
    selectDownList (attr) {
      if (this[attr + 'Index'] < this[attr + 'List'].length - 1) {
        this[attr + 'Index'] += 1
        this[attr + 'Select'] = true
        this.data[attr] = this[attr + 'List'][this[attr + 'Index']].name
        if (this[attr + 'Index'] > 2) {
          this.$refs.dropdown.scrollTop += 48
        }
      }
    },
    // 按下方向键向上
    selectUpList (attr) {
      if (this[attr + 'Index'] > 0) {
        this[attr + 'Index'] -= 1
        this[attr + 'Select'] = true
        this.data[attr] = this[attr + 'List'][this[attr + 'Index']].name
        if (this[attr + 'Index'] < this[attr + 'List'].length - 3) {
          this.$refs.dropdown.scrollTop -= 48
        }
      }
    },
    keyEnter (attr) {
      this[attr + 'List'] = []
    },
    // 当点击输入框时，如果不为空，调用接口
    onClick (attr) {
      if (this[attr + 'List'].length === 0) {
        this.cancelToken()
        if (attr === 'school') {
          // 清除另一个输入框的下拉框
          this.schoolDistrictList = []
          // 如果不为空，调用接口
          if (this.data.school !== '') {
            this.schoolIndex = -1
            this.getSchoolList()
          }
        } else if (attr === 'schoolDistrict') {
          // 清除另一个输入框的下拉框
          this.schoolList = []
          // 如果不为空，调用接口
          if (this.data.school !== '') {
            this.schoolDistrictIndex = -1
            this.getSchoolDistrictList()
          }
        }
      }
    },
    // 点击其他区域，收起列表
    clearList () {
      this.cancelToken()
      this.schoolList = []
      this.schoolDistrictList = []
    },
    // 取消请求
    cancelToken () {
      if (this.source) {
        this.source.cancel()
      }
    },
    upload (attr, val) {
      if (val) {
        if (attr === 'identify') {
          this.data.identifyCard = val
          this.uploadIdentityImgStatus = 1
          this.uploadIdentityImgError = false
        } else if (attr === 'student') {
          this.data.studentCard = val
          this.uploadStudentImgStatus = 1
          this.uploadStudentImgError = false
        } else {
          this.data.selfHoldCard = val
          this.uploadSelfHoldImgStatus = 1
          this.uploadSelfHoldImgError = false
        }
      } else {
        if (attr === 'identify') {
          this.data.identifyCard = val
          this.uploadIdentityImgStatus = 2
          this.uploadIdentityImgError = true
        } else if (attr === 'student') {
          this.data.studentCard = val
          this.uploadStudentImgStatus = 2
          this.uploadStudentImgError = true
        } else {
          this.data.selfHoldCard = val
          this.uploadSelfHoldImgStatus = 2
          this.uploadSelfHoldImgError = true
        }
      }
    }
  },
  created () {
    document.addEventListener('click', this.clearList)
  },
  mounted () {
    // 如果有传入的数据，初始化选中状态
    for (let key in this.data) {
      if (this.data[key] && this.data[key] !== '') {
        this[`${key}Status`] = 1
      }
    }
    // 初始化数据
    this.data = this.parentData
  },
  deactivated () {
    document.removeEventListener('click', this.clearList)
  }
}
</script>

<style scoped>
.title {
  line-height: 22px;
  font-size: 16px;
  font-weight: bold;
  padding-left: 18px;
  padding-bottom: 16px;
  position: relative;
}

.title:before {
  content: '';
  display: block;
  width: 4px;
  height: 15px;
  background-color: #ff600a;
  position: absolute;
  top: 4px;
  left: 0;
}

.label {
  line-height: 20px;
  margin-top: 24px;
}

.input {
  height: 48px;
  border: 1px solid #d7d7d7;
  border-radius: 2px;
  box-sizing: border-box;
  margin-top: 12px;
  padding: 0 15px;
}

.input-short {
  width: 288px;
  margin-right: 24px;
}

.input-short:last-child {
  margin-right: 0;
}

.choose-group {
  height: 48px;
  margin-top: 12px;
  overflow: hidden;
}

.choose {
  float: left;
  width: 158px;
  height: 46px;
  line-height: 46px;
  border: 1px solid #d7d7d7;
  border-radius: 2px;
  text-align: center;
  color: #a5a5a5;
  margin-right: 24px;
  cursor: pointer;
}

.choose:last-child {
  margin-right: 0;
}

.chooseActive {
  color: #333;
  border: 1px solid #ff600a;
  background: url(../../assets/images/icon_check.png) no-repeat right top;
}

.input-long {
  width: 600px;
}

.upload {
  margin-top: 60px;
}

.select-dropdown {
  width: 600px;
  max-height: 240px;
  overflow: auto;
  border: 1px solid #d7d7d7;
  background-color: #fff;
  box-sizing: border-box;
  position: absolute;
  z-index: 2;
}

.select-dropdown li {
  height: 48px;
  line-height: 48px;
  padding-left: 15px;
  cursor: pointer;
}

.active {
  background-color: #f6f6f6;
}
</style>
